//
//  PhotoViewController.m
//  WOFishingBoat
//
//  Created by 郑逸凯 on 2018/12/27.
//  Copyright © 2018年 郑逸凯. All rights reserved.
//

#import "PhotoViewController.h"
#import "PhotoCollectionViewCell.h"
#import "PhotoSectionModel.h"
#import "PhotoDataModel.h"
#import "MWPhotoBrowser.h"
#import "MWPhoto.h"
#import "PhotoListBottomView.h"
#import "DateSearchBar.h"
#import <MJRefresh/MJRefresh.h>
#import "AlbumModel.h"
#import "CalendarController.h"
#import "PhotoCollectionHeadView.h"
#import "PhotoToolBottomBar.h"
#import "YACalendarDate.h"
#import "DownloadManager.h"
#import <AFNetworking/AFNetworking.h>
#import <VIMediaCache/VIMediaCache.h>

#define PHOTO_SELECT_MAX_COUNT 20
#define PHOTO_DOWNLOAD_TIMEOUT 5
#define VIDEO_DOWNLOAD_TIMEOUT 60
#define COLLECTION_MARGIN 20

@interface PhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MWPhotoBrowserDelegate,PhotoListBottomViewDelegate,PhotoToolBottomBarDelegate,CalendarControllerDelegate>

@property (nonatomic,strong)AlbumModel *albumModel;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIButton *selectionButton;
@property (nonatomic,strong)DateSearchBar *dateSearchBar;
@property (nonatomic,strong)PhotoToolBottomBar *toolBottomBar;
@property (nonatomic,strong)PhotoDataModel *photoDataModel;
@property (nonatomic,strong)RequestSession *photoListRequest;
@property (nonatomic,strong)RequestSession *photoDeleteRequest;
@property (nonatomic,assign)NSInteger currentPage;
@property (nonatomic,assign)NSString *currentDateString;
@property (nonatomic) BOOL selectionMode;
@property (nonatomic) BOOL needReloadfromBorwser;
//photoBrowser
@property (nonatomic,strong)PhotoListBottomView *browserPhotoListBottomView;
@property (nonatomic,strong)PhotoToolBottomBar *browserToolBottomBar;
@property (nonatomic,strong)MWPhotoBrowser *photoBrowser;
@end

@implementation PhotoViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self performLayout];
    NSLog(@"%@",[VICacheManager cacheDirectory]);
    
    self.navigationItem.title = self.albumModel.shipName;
    
    
    
    [self resetCurrentDateAndPage];
    [self requestPhotoList];
    @weakify(self);
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self resetCurrentDateAndPage];
        [self requestPhotoList];
    }];
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        [self requestPhotoList];
    }];
    
    // Do any additional setup after loading the view.
}

- (instancetype)initWithModel:(id)model {
    if (self = [super init]) {
        if (model && [model isKindOfClass:[AlbumModel class]]) {
            _albumModel = model;
        }
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needReloadfromBorwser) {
        self.needReloadfromBorwser = NO;
        [self.photoDataModel generatePhotoSectionByCurrentPhotoArray];
        [self.collectionView reloadData];
    }
}

#pragma mark - Public Methods
#pragma mark - Responder Actions
- (void)selectAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.selectionMode = !self.selectionMode;
    self.toolBottomBar.hidden = !self.selectionMode;
    self.dateSearchBar.userInteractionEnabled = !self.selectionMode;
    [self.collectionView reloadData];
}

- (void)selectSectionAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    NSInteger section = sender.tag;
     PhotoSectionModel *model = [self.photoDataModel.photoSectionModels tm_safeObjectAtIndex:section];
    model.isSelected = sender.selected;
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:section]];
}

- (void)searchDateAction {
    CalendarController *calendarVC = [[CalendarController alloc] init];
    calendarVC.delegate = self;
    [self.navigationController pushViewController:calendarVC animated:YES];
}
#pragma mark - CalendarControllerDelegate

- (void)selectDayConfirmed:(NSDate *)date {
    [self resetCurrentDateAndPage];
    self.currentDateString = [YACalendarDate formatterString:@"yyyyMMdd" Date:date];
    [self.collectionView setContentOffset:CGPointMake(0, 0)];
    [self requestPhotoList];
}

#pragma mark - PhotoToolBottomBarDelegate

- (void)deleteClickedPhotoToolBottomBar:(PhotoToolBottomBar *)photoToolBottomBar {
    NSArray *selectedPhotoArray = nil;
    if (photoToolBottomBar == self.browserToolBottomBar) {
        PhotoModel *model = self.photoDataModel.photoArray[self.photoBrowser.currentIndex];
        selectedPhotoArray = @[model];
    }else {
        selectedPhotoArray = [self.photoDataModel generatsSelectedPhotoArray];
    }
    if (selectedPhotoArray.count == 0) {
        [YAToast showTouchableTipMessageInView:[NSString stringWithFormat:@"请选择照片"] timer:1];
        return ;
    }
    if (selectedPhotoArray.count > PHOTO_SELECT_MAX_COUNT) {
        [YAToast showTouchableTipMessageInView:[NSString stringWithFormat:@"当前操作最多只可选择%i张照片",PHOTO_SELECT_MAX_COUNT] timer:2];
        return ;
    }
    NSString *message = selectedPhotoArray.count == 1?@"删除这张照片":[NSString stringWithFormat:@"删除这%li张照片",selectedPhotoArray.count];
    [self jxt_showActionSheetWithTitle:@"" message:@"这些照片将从云端相册中删除" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.addActionDestructiveTitle(message).addActionCancelTitle(@"取消");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 0) {
            [self requestDeletePhotoList:selectedPhotoArray];
        }
    }];
    
}

- (void)downloadClickedPhotoToolBottomBar:(PhotoToolBottomBar *)photoToolBottomBar {
    
    void (^authorizationCompletionBlock)(void) = ^(){
        if (photoToolBottomBar == self.browserToolBottomBar) {
            PhotoModel *model = [self.photoDataModel.photoArray tm_safeObjectAtIndex: self.photoBrowser.currentIndex];
            MBProgressHUD *hud  = [YAToast showActivityMessageInView:@"" timer: model.isVideo ?VIDEO_DOWNLOAD_TIMEOUT : PHOTO_DOWNLOAD_TIMEOUT];
            [[DownloadManager sharedInstance] download:@[model.mwBigPhoto] progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completionHandler:^(NSArray * _Nonnull errorArray) {
                [hud hide:YES];
                if (errorArray.count > 0) {
                    [YAToast showTouchableTipMessageInView:[NSString stringWithFormat:@"其中%li张下载失败，其余已下载，你可以到手机相册中查看",errorArray.count] timer:2];
                }else {
                    [YAToast showTouchableTipMessageInView:@"已下载，你可以到手机相册中查看" timer:2];
                }
            }];
            
//           [model.mwBigPhoto downloadImageCompletionHandler:^(UIImage * image) {
//               if (image) {
//                   [[DownloadManager sharedInstance] saveImage:image completionHandler:^(NSError * _Nonnull error) {
//                        [hud hide:YES];
//                       if (error) {
//                           [YAToast showTouchableTipMessageInView:error.domain timer:1];
//                       }else {
//                           [YAToast showTouchableTipMessageInView:@"已下载，你可以到手机相册中查看" timer:2];
//                       }
//                   }];
//               }else {
//                   [hud hide:YES];
//                   [YAToast showTouchableTipMessageInView:@"下载照片失败" timer:1];
//               }
//           }];
        }else {
            NSArray *selectedPhotoArray = [self.photoDataModel generatsSelectedPhotoArray];
            if (selectedPhotoArray.count > PHOTO_SELECT_MAX_COUNT) {
                [YAToast showTouchableTipMessageInView:[NSString stringWithFormat:@"前操作最多只可选择%i张照片",PHOTO_SELECT_MAX_COUNT] timer:2];
                return ;
            }
            NSMutableArray *mwPhotos = [NSMutableArray array];
            NSInteger timeout = 0;
            for (PhotoModel *model in selectedPhotoArray) {
                if (model.mwBigPhoto.isVideo) {
                    timeout += VIDEO_DOWNLOAD_TIMEOUT;
                }else {
                    timeout += PHOTO_DOWNLOAD_TIMEOUT;
                }
                [mwPhotos addObject:model.mwBigPhoto];
            }
            NSInteger selectedCount = mwPhotos.count;
            MBProgressHUD *hud  = [YAToast showActivityMessageInView:[NSString stringWithFormat:@"下载中%i/%li",0,selectedCount] timer:(int)(timeout)];
            [[DownloadManager sharedInstance] download:mwPhotos progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                hud.labelText = [NSString stringWithFormat:@"下载中%li/%li",receivedSize,expectedSize];
            } completionHandler:^(NSArray * _Nonnull errorArray) {
                [hud hide:YES];
                if (errorArray.count > 0) {
                    [YAToast showTouchableTipMessageInView:[NSString stringWithFormat:@"其中%li张下载失败，其余已下载，你可以到手机相册中查看",errorArray.count] timer:2];
                }else {
                    [YAToast showTouchableTipMessageInView:@"已下载，你可以到手机相册中查看" timer:2];
                }
            }];
            
        }
    };
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusAuthorized) {
                authorizationCompletionBlock();
            }else {
                [self jxt_showAlertWithTitle:@"提示"
                                     message:[NSString stringWithFormat: @"请在iPhone的”设置-隐私-照片“选项中，允许%@访问你的手机相册",YA_ALBUM_NAME]
                           appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
                               alertMaker.
                               //                               addActionCancelTitle(@"取消").
                               addActionDefaultTitle(@"确认");
                           } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
                               
                           }];
            }
        });
        
    }];

}

#pragma mark - PhotoListBottomViewDelegate

- (void)scrolledToIndex:(NSInteger)index photoListBottomView:(PhotoListBottomView *)photoListBottomView {
    [self.photoBrowser setCurrentPhotoIndex:index];
}

#pragma mark - UICollectionViewDelegates
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        PhotoCollectionHeadView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoCollectionHeadView" forIndexPath:indexPath];
       
        
        PhotoSectionModel *model = [self.photoDataModel.photoSectionModels tm_safeObjectAtIndex:indexPath.section];
        header.selectButton.hidden = !self.selectionMode;
        if (self.selectionMode) {
            if ( header.selectButton.allTargets.count == 0) {
                [header.selectButton addTarget:self action:@selector(selectSectionAction:) forControlEvents:UIControlEventTouchUpInside];
            }
            header.selectButton.selected = model.isSelected;
            header.selectButton.tag = indexPath.section;
        }
        header.timeLabel.text = model.sectionTime;
        return header;
    } else {
        return nil;
    }
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.photoDataModel.photoSectionModels.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    PhotoSectionModel *model = [self.photoDataModel.photoSectionModels tm_safeObjectAtIndex:section];
    return model.photoArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return (CGSize){SCREEN_WIDTH,36};
}




- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PhotoCollectionViewCell*cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCollectionViewCell" forIndexPath:indexPath];
    if (!cell ) {
        NSLog(@"cell为空,创建cell");
        cell = [[PhotoCollectionViewCell alloc] init];
    }
    PhotoSectionModel *sectionModel = [self.photoDataModel.photoSectionModels tm_safeObjectAtIndex:indexPath.section];
    PhotoModel *model = [sectionModel.photoArray tm_safeObjectAtIndex:indexPath.row];
    cell.isNormalStyle = YES;
    cell.selectionMode = self.selectionMode;
    cell.photoModel = model;
    cell.isSelected = model.isSelected;
    cell.gridController = self;
    
    cell.index = indexPath.row;

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self jumpToPhotoBrowserIndex:indexPath];
}

#pragma mark -Request

- (void)requestDeletePhotoList:(NSArray *)photoArray {
    @weakify(self);
    NSMutableArray *mutPhotoArray = [NSMutableArray array];
    for (PhotoModel *model in photoArray) {
        NSDictionary *dic = @{
                              @"id":model.boatID,
                              @"imgName":[model imageName]
                              };
        [mutPhotoArray addObject:dic];

    }
    NSString *urlStr = WO_PATH_PHOTO_DELETE;
//    NSString *urlStr = @":5088/pic/deleteByImgName";
//    NSString *urlStr = @":5088/pic/delete";
    
    self.photoDeleteRequest.isJsonRequest = YES;
    [self.photoDeleteRequest postWithURLString:WO_URL(urlStr) parameters:mutPhotoArray completionHandler:^(id responseObject, NSError *error) {
        @strongify(self);
        if (!error ) {
            [YAToast showTouchableTipMessageInView:@"删除成功"];
            for (PhotoModel *model in photoArray) {
                model.isReadyToDelete = YES;
            }
            [self deleteSuccess];
        }else {
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
    
}

- (void)requestPhotoList {
    @weakify(self);
    self.currentPage++;
    NSString *urlStr = WO_PATH_PHOTO_LIST;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                                  @"startTime":@"20181101",
                                                                                  @"endTime":self.currentDateString,
                                                                                  @"page":@(self.currentPage),
                                                                                  
                                                                                  }];
    if (![self.albumModel.shipName isEqualToString:@"all"]) {
        [params setObject:self.albumModel.shipName forKey:@"id"];
    }

    [self.photoListRequest postWithURLString:WO_URL(urlStr) parameters:params completionHandler:^(id responseObject, NSError *error) {
        @strongify(self);
        if (self.collectionView.mj_header.isRefreshing) {
            [self.collectionView.mj_header endRefreshing];
        }
        if (self.collectionView.mj_footer.isRefreshing) {
            [self.collectionView.mj_footer endRefreshing];
        }
        if (!error ) {
            NSDictionary *data = [responseObject tm_dictionaryForKey:@"data"];
            NSArray *listArray = [data tm_arrayForKey:@"screenShotInfoVOList"];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *boatDic in listArray) {
                [array addObject:[PhotoModel yy_modelWithDictionary:boatDic]];
            }
            if (self.currentPage == 1) {
                self.photoDataModel = nil;
                //如果是上拉刷新将数据模型重置
            }
            [self.photoDataModel generatePhotoSectionByAppendArray:array];
            
            [self.collectionView reloadData];
        }else {
            self.currentPage--;
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
}

#pragma mark - Private Methods

- (void)performLayout {
    
    [self.dateSearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(Height_TopBar + 10);
        make.left.equalTo(self.view).with.offset(COLLECTION_MARGIN);
        make.right.equalTo(self.view).with.offset(-COLLECTION_MARGIN);
        make.height.mas_equalTo(30);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.dateSearchBar.mas_bottom).with.offset(15);
        make.left.equalTo(self.view).with.offset(COLLECTION_MARGIN);
        make.right.equalTo(self.view).with.offset(-COLLECTION_MARGIN);
        make.bottom.equalTo(self.view);
    }];
    
    [self.toolBottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(50 + Height_BottomSafe);
    }];
}

- (void)setupSubviews {
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView: self.selectionButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.view addSubview:self.dateSearchBar];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.toolBottomBar];
}

- (void)deleteSuccess {
//    双层遍历去掉已经删除的photo
//    for (PhotoSectionModel *sectionModel in self.photoDataModel.photoSectionModels) {
//        if (sectionModel.isReadyToDelete) {
//            sectionModel.isReadyToDelete = NO;
//            for (PhotoModel *model in [sectionModel.photoArray mutableCopy]) {
//                if (model.isReadyToDelete) {
//                    [sectionModel.photoArray removeObject:model];
//                }
//            }
//        }
//    }
    for (PhotoModel *model in [self.photoDataModel.photoArray mutableCopy]) {
        if (model.isReadyToDelete == YES) {
            [self.photoDataModel.photoArray removeObject:model];
        }
    }
    if ([self.navigationController topViewController] == self) {
        [self.photoDataModel generatePhotoSectionByCurrentPhotoArray];
        [self.collectionView reloadData];
    }else {
        self.needReloadfromBorwser = YES;
        [self.photoBrowser reloadData];
        [self.browserPhotoListBottomView reloadData];
    }
   
}

#pragma mark - Setters and Getters

- (RequestSession *)photoListRequest {
    if (!_photoListRequest) {
        _photoListRequest = [[RequestSession alloc] init];
    }
    return _photoListRequest;
}

- (RequestSession *)photoDeleteRequest {
    if (!_photoDeleteRequest) {
        _photoDeleteRequest = [[RequestSession alloc] init];
    }
    return _photoDeleteRequest;
}

- (PhotoDataModel *)photoDataModel {
    if (!_photoDataModel) {
        _photoDataModel = [[PhotoDataModel alloc] init];
    }
    return _photoDataModel;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGRect collectionViewFrame= CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 100);
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        // 设置UICollectionView为横向滚动
//        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        // 每一行cell之间的间距
        flowLayout.minimumLineSpacing = 1;
        // 每一列cell之间的间距
        flowLayout.minimumInteritemSpacing = 1;
        // 设置第一个cell和最后一个cell,与父控件之间的间距
        flowLayout.sectionInset = UIEdgeInsetsMake(1, 0, 1, 0);
        
        //    flowLayout.minimumLineSpacing = 1;// 根据需要编写
        //    flowLayout.minimumInteritemSpacing = 1;// 根据需要编写
        CGFloat itemHeight = (SCREEN_WIDTH - COLLECTION_MARGIN * 2 - 5)/4;
        flowLayout.itemSize = CGSizeMake(itemHeight, itemHeight);// 该行代码就算不写,item也会有默认尺寸
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayout];
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"PhotoCollectionViewCell"];
        [collectionView registerClass:[PhotoCollectionHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoCollectionHeadView"];
        
        _collectionView = collectionView;
    }
    return _collectionView;
}

- (UIButton *)selectionButton {
    if (!_selectionButton) {
        _selectionButton = [self createSelectButton];
        [_selectionButton addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectionButton;
}

- (UIButton *)createSelectButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"选择" forState:UIControlStateNormal];
    [button setTitle:@"取消" forState:UIControlStateSelected];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setTitleColor:RGB16(0x2988fc) forState:UIControlStateNormal];
    return button;
}

- (DateSearchBar *)dateSearchBar {
    if (!_dateSearchBar) {
        _dateSearchBar = [[DateSearchBar alloc] init];
        [_dateSearchBar addTarget:self action:@selector(searchDateAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dateSearchBar;
}

- (PhotoToolBottomBar *)toolBottomBar {
    if (!_toolBottomBar) {
        _toolBottomBar = [[PhotoToolBottomBar alloc] initWithFrame:CGRectZero];
        _toolBottomBar.hidden = YES;
        _toolBottomBar.delegate = self;
    }
    return _toolBottomBar;
}

- (PhotoToolBottomBar *)browserToolBottomBar {
    if (!_browserToolBottomBar) {
        _browserToolBottomBar = [[PhotoToolBottomBar alloc] initWithFrame:CGRectZero];
        _browserToolBottomBar.delegate = self;
    }
    return _browserToolBottomBar;
}

- (PhotoListBottomView *)browserPhotoListBottomView {
    if (!_browserPhotoListBottomView) {
        _browserPhotoListBottomView = [[PhotoListBottomView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        _browserPhotoListBottomView.delegate = self;
    }
    return _browserPhotoListBottomView;
}

- (MWPhotoBrowser *)photoBrowser {
    if (!_photoBrowser) {
        // Create browser (must be done each time photo browser is
        // displayed. Photo browser objects cannot be re-used)
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];

        // Set options
        browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        
        // Customise selection images to change colours if required
        //    browser.customImageSelectedIconName = @"ImageSelected.png";
        //    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        
        [browser showNextPhotoAnimated:YES];
        [browser showPreviousPhotoAnimated:YES];
        _photoBrowser = browser;
    }
    return _photoBrowser;
}
#pragma mark - Helper

- (void)resetCurrentDateAndPage {
    self.currentPage = 0;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    self.currentDateString = [formatter stringFromDate: [NSDate date]];
}

#pragma mark - jumpToPhotoBrowser
- (void)jumpToPhotoBrowserIndex:(NSIndexPath*)indexPath {
    // Create array of MWPhoto objects
    //1、获取index
    NSInteger index = [self.photoDataModel indexAtTotalWithSection:indexPath.section row:indexPath.row];
   
    //2、设置底部栏
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
    bottomView.backgroundColor = [UIColor whiteColor];
    //测试中间条
//    UIView *centerLine = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 2)/2, 0, 2, 80)];
//    centerLine.backgroundColor = [UIColor redColor];
//    [bottomView addSubview:centerLine];
    //3、刷新broser
    [self.photoBrowser reloadData];
    self.browserPhotoListBottomView.photoArray = self.photoDataModel.photoArray;
    [self.browserPhotoListBottomView setCurrentPhotoIndex:index];
    
    self.browserPhotoListBottomView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    self.browserToolBottomBar.frame = CGRectMake(0, 40, SCREEN_WIDTH, 50);
    [bottomView addSubview:self.browserPhotoListBottomView];
    [bottomView addSubview:self.browserToolBottomBar];

    self.photoBrowser.customBottomBar = bottomView;
    // Optionally set the current visible photo before displaying
    [self.photoBrowser setCurrentPhotoIndex:index];
    
    
    // Present
    [self.navigationController pushViewController:self.photoBrowser animated:YES];
    
    // Manipulate
    
}



- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photoDataModel.photoArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photoDataModel.photoArray.count) {
        PhotoModel *model = [self.photoDataModel.photoArray objectAtIndex:index];
        return model.mwBigPhoto;
    }
    return nil;
}

- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
    PhotoModel *model = [self.photoDataModel.photoArray objectAtIndex:index];
    return model.displayName;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    [self.browserPhotoListBottomView setCurrentPhotoIndex:index];
}

@end
